/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package schedulingScheme;

import helper.BagWithNumbers;
import helper.Config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

/**
 *
 * @author Andrzej
 */
public class GeneticOperations {

    private static final Random random = Config.getSalt();

    public static <T> T tournament(List<T> population, Comparator<T> fitnessValue, int tournamentSize, double p) {
        List<T> tournament = new ArrayList<T>(tournamentSize);

        BagWithNumbers bwn = new BagWithNumbers(population.size());
        for (int j = 0; j < tournamentSize; j++) {

            T chromosome = population.get(bwn.drawNumber());
            tournament.add(chromosome);
        }
        Collections.sort(tournament, Collections.reverseOrder(fitnessValue));

        double p2 = 1;
        double r = random.nextDouble();
        for (int j = 0; j < tournamentSize; j++) {
            if (r < p) {
                return tournament.get(j);
            }
            p2 = p2 * (1 - p);
            p = p + p2;
        }
        return tournament.get(tournament.size() - 1);
    }


}
